package com.fancon.android.gardenjokesx;

import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.PopupWindow;

import com.fancon.android.activity.FanconBaseFragmentActivity;
import com.fancon.android.emoji.EmojiDockPanel;
import com.fancon.android.emoji.EmojiUtil;
import com.fancon.android.emoji.IRichGlobalState;
import com.fancon.android.emoji.widget.IRichText;
import com.fancon.android.emoji.widget.RichEditText;
/**
 * Base activity for GardenJokes
 * @author binhbt
 *
 */

public class GardenJokesBaseFragmentActivity extends FanconBaseFragmentActivity implements  IRichText{
	protected PopupWindow popupWindow;
	//for Emoji keyboard
	private EmojiUtil mEmojiUtil;
	private EmojiDockPanel panel = null;	
	private Boolean isKeyBoardShow = false;
	protected int keyboardHeight = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mEmojiUtil = ((IRichGlobalState)getApplication()).getEmojiUtil();
		bindKeyBoard();
	}

	@Override
	public EmojiUtil getEmojiUtil() {
		// TODO Auto-generated method stub
		return mEmojiUtil;
	}

	@Override
	public void doFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		if(!hasFocus){
			hideEmojiPanel();
		}
	}
	protected void bindKeyBoard(){
		final FrameLayout rootContent = (FrameLayout) findViewById(android.R.id.content);
		rootContent.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					Rect r = new Rect();

					@Override
					public void onGlobalLayout() {
						int currentBottom = r.bottom;
						rootContent.getWindowVisibleDisplayFrame(r);
						if (currentBottom == r.bottom) {
							// Log.d(TAG, "SAME Height");
							return; // nothing changed
						}
						// Log.d(TAG, "DIFFERENT Height");
						int heightDiff = rootContent.getRootView().getHeight()
								- r.bottom;
						keyboardHeight = heightDiff;
						if (heightDiff > 100) { // if more than 100 pixels, its
												// probably
												// a keyboard...
							Log.d("xxxx", "Keyboard visible");
							showEmojiPanel(heightDiff);
						} else {
							// Log.d(TAG, "Keyboard invisible");
							hideEmojiPanel();
						}
					}
				});
	}
	protected void showEmojiPanel(int keyboardHeight) {
		View focusingView = getCurrentFocus();
		if (focusingView instanceof RichEditText) {
			if (!isKeyBoardShow) {
				panel = new EmojiDockPanel(focusingView, (RichEditText) focusingView);
				panel.showPanel(keyboardHeight);
				isKeyBoardShow = true;
			}
		}
	}

	protected void hideEmojiPanel() {
		if (isKeyBoardShow) {
			panel.dismiss();
			isKeyBoardShow = false;
		}
	}
}
